package fun.codedesign.yinxue.code.engine.jdt;

import org.eclipse.jdt.core.dom.*;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * <a href="https://blog.51cto.com/u_16213336/6989656">...</a>
 */
public class WriteNewMethod {

    public static void main(String[] args) {
        step1();
    }

    public static void step1() {
        // 创建ASTParser实例
        ASTParser parser = ASTParser.newParser(AST.JLS11);
        // 设置ASTParser的输入和选项
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(CodeExample.EXAMPLE1.toCharArray());
        parser.setResolveBindings(true);
        // 获取AST，并将其转换为可执行的Java源代码
        CompilationUnit compiledUnit = (CompilationUnit) parser.createAST(null);
        compiledUnit.accept(new AstChangeVisitor());
        String newCode = compiledUnit.toString();
        System.out.println(newCode);
        // 创建一个新的Java文件
        File file = new File("GeneratedClass.java");
        // 写入生成的Java源代码到文件中
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(newCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testCompilationUnit1() {
        ASTParser parser = ASTParser.newParser(AST.JLS11);
        // 设置ASTParser的输入和选项
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource("class Abc { }".toCharArray());
        parser.setResolveBindings(true);

        // 获取AST，并将其转换为可执行的Java源代码
        CompilationUnit compiledUnit = (CompilationUnit) parser.createAST(null);
        compiledUnit.accept(new AstChangeVisitor());
        String newCode = compiledUnit.toString();
        System.out.println(newCode);
    }

    // https://github.com/eclipse-jdt/eclipse.jdt.core/blob/master/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/dom/ASTTest.java
    public static void createCompilationUnit2() {
        AST ast = AST.newAST(AST.JLS8);
        CompilationUnit compilationUnit = ast.newCompilationUnit();

        PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
        packageDeclaration.setName(ast.newName(new String[]{"com","snowfure"}));

        compilationUnit.setPackage(packageDeclaration);

        TypeDeclaration typeDeclaration = ast.newTypeDeclaration();
        typeDeclaration.setName(ast.newSimpleName("Abc"));

        compilationUnit.types().add(typeDeclaration);

        System.out.println(compilationUnit);
    }
}
